package com.morimoto.rmlib;

import android.view.animation.Interpolator;

/**
 * 
 * @author Ryohei Morimoto
 *
 */
public class Animation {
	
	//----- field -----//
	
	protected int mDuration;
	protected Interpolator mInterpolator;
	protected long mStartTimestamp;
	protected boolean mPlaying;
	protected boolean mReverse;
	private float mFromVal;
	private float mToVal;

	//----- Constructor -----//
	
	public Animation(float fromDeg, float toDeg, int duration, Interpolator interpolator) {
		mDuration = duration;
		mInterpolator = interpolator;
		mPlaying = false;
		mReverse = false;
		mFromVal = fromDeg;
		mToVal = toDeg;
	}

	//----- public method -----//
	
	public void start() {
		mStartTimestamp = System.currentTimeMillis();
		mReverse = false;
		mPlaying = true;
	}
	
	public void reverse() {
		mStartTimestamp = System.currentTimeMillis();
		mReverse =  true;
		mPlaying = true;
	}
	
	public boolean isPlaying() {
		return mPlaying;
	}
	
	public float interpolate() {
		if (isPlaying()) {
			final long timestamp = System.currentTimeMillis();
			final float t = (timestamp - mStartTimestamp) / (float)mDuration; 
			final float val = mInterpolator.getInterpolation(t);
			float deg;
			if (mReverse) {
				deg = mToVal + val * (mFromVal - mToVal);
			} else {
				deg = mFromVal + val * (mToVal - mFromVal);
			}
			if (1.0f <= t) {
				mPlaying = false;
			}
			return deg;
		} else {
			return mReverse ? mFromVal : mToVal;
		}
	}
}
